import React, { useState, useEffect, useCallback, useMemo } from "react";
import { ConductorSpecAPI } from "@/api/ConductorSpec";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Plus,
  Edit,
  Trash2,
  X,
  MoreHorizontal,
  Cable,
  ChevronLeft,
  ChevronRight,
  Search
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Textarea } from "@/components/ui/textarea";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";



// 表单组件保持不变
const ConductorSpecForm = ({ spec, onSubmit, onCancel }) => {
  const [formData, setFormData] = useState(
    spec
      ? {
          ...spec,
          breakingForceKn: spec.breakingForceKn ?? null,
          unitLoadNPerMMm2: spec.unitLoadNPerMMm2 ?? null,
          crossSectionalAreaMm2: spec.crossSectionalAreaMm2 ?? null,
          thermalExpansionCoeffPerC: spec.thermalExpansionCoeffPerC ?? null,
          elasticModulusMpa: spec.elasticModulusMpa ?? null,
          designOperatingStressMpa: spec.designOperatingStressMpa ?? null,
          outerDiameterMm: spec.outerDiameterMm ?? null,
          weightPerMeterNPerM: spec.weightPerMeterNPerM ?? null,
          windLoadShapeFactor: spec.windLoadShapeFactor ?? 1.2,
          notes: spec.notes ?? "",
        }
      : {
          model: "",
          type: "ACSR",
          breakingForceKn: null,
          unitLoadNPerMMm2: null,
          crossSectionalAreaMm2: null,
          thermalExpansionCoeffPerC: null,
          elasticModulusMpa: null,
          designOperatingStressMpa: null,
          outerDiameterMm: null,
          weightPerMeterNPerM: null,
          windLoadShapeFactor: 1.2,
          notes: "",
        }
  );

  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleNumberChange = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value === "" ? null : parseFloat(value),
    }));
  };

  const calculateUnitLoad = useCallback(() => {
    const weight = parseFloat(formData.weightPerMeterNPerM);
    const area = parseFloat(formData.crossSectionalAreaMm2);

    if (weight > 0 && area > 0) {
      return (weight / area).toFixed(6);
    }
    return null;
  }, [formData.weightPerMeterNPerM, formData.crossSectionalAreaMm2]);

  const calculatedUnitLoad = calculateUnitLoad();

  const handleSubmit = (e) => {
    e.preventDefault();

    const submitData = {
      ...formData,
      unitLoadNPerMMm2: calculatedUnitLoad
        ? parseFloat(calculatedUnitLoad)
        : null,
    };

    onSubmit(submitData);
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="w-full max-w-2xl bg-white rounded-lg shadow-xl">
        <div className="p-6 border-b">
          <div className="flex justify-between items-center">
            <div className="flex items-center gap-2">
              <Cable className="w-5 h-5" />
              <h3 className="text-lg font-semibold">
                {spec ? "编辑导线规格" : "新建导线规格"}
              </h3>
            </div>
            <Button variant="ghost" size="icon" onClick={onCancel}>
              <X className="w-4 h-4" />
            </Button>
          </div>
        </div>
        <div className="p-6">
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="model">导线型号*</Label>
                <Input
                  id="model"
                  value={formData.model}
                  onChange={(e) => handleChange("model", e.target.value)}
                  required
                />
              </div>
              <div>
                <Label htmlFor="type">导线类型</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value) => handleChange("type", value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ACSR">钢芯铝绞线</SelectItem>
                    <SelectItem value="AAC">全铝绞线</SelectItem>
                    <SelectItem value="AAAC">全铝合金绞线</SelectItem>
                    <SelectItem value="ACAR">铝包钢芯铝绞线</SelectItem>
                    <SelectItem value="ACCC">碳纤维复合芯导线</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="breakingForceKn">额定拉断力 (kN)*</Label>
                <Input
                  id="breakingForceKn"
                  type="number"
                  step="0.01"
                  value={formData.breakingForceKn ?? ""}
                  onChange={(e) =>
                    handleNumberChange("breakingForceKn", e.target.value)
                  }
                  required
                />
              </div>
              <div>
                <Label htmlFor="crossSectionalAreaMm2">总截面积 (mm²)*</Label>
                <Input
                  id="crossSectionalAreaMm2"
                  type="number"
                  step="0.01"
                  value={formData.crossSectionalAreaMm2 ?? ""}
                  onChange={(e) =>
                    handleNumberChange("crossSectionalAreaMm2", e.target.value)
                  }
                  required
                />
              </div>
              <div>
                <Label htmlFor="outerDiameterMm">外径 (mm)</Label>
                <Input
                  id="outerDiameterMm"
                  type="number"
                  step="0.1"
                  value={formData.outerDiameterMm ?? ""}
                  onChange={(e) =>
                    handleNumberChange("outerDiameterMm", e.target.value)
                  }
                />
              </div>
              <div>
                <Label htmlFor="weightPerMeterNPerM">单位重量 (N/m)*</Label>
                <Input
                  id="weightPerMeterNPerM"
                  type="number"
                  step="0.01"
                  value={formData.weightPerMeterNPerM ?? ""}
                  onChange={(e) =>
                    handleNumberChange("weightPerMeterNPerM", e.target.value)
                  }
                  required
                />
                <p className="text-xs text-gray-500 mt-1">
                  单位长度自重力，用于风偏计算
                </p>
              </div>

              <div>
                <Label>导线比载 (N/(m·mm²))</Label>
                <div className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm">
                  {calculatedUnitLoad ? (
                    <span className="text-green-600 font-mono">
                      {calculatedUnitLoad}
                    </span>
                  ) : (
                    <span className="text-gray-400">
                      需先填写单位重量和截面积
                    </span>
                  )}
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  自动计算：单位重量 ÷ 截面积
                </p>
              </div>

              <div>
                <Label htmlFor="windLoadShapeFactor">风载体型系数</Label>
                <Input
                  id="windLoadShapeFactor"
                  type="number"
                  step="0.01"
                  value={formData.windLoadShapeFactor ?? ""}
                  onChange={(e) =>
                    handleNumberChange("windLoadShapeFactor", e.target.value)
                  }
                />
                <p className="text-xs text-gray-500 mt-1">通常架空绞线取1.2</p>
              </div>
              <div>
                <Label htmlFor="designOperatingStressMpa">
                  设计运行应力 (MPa)*
                </Label>
                <Input
                  id="designOperatingStressMpa"
                  type="number"
                  step="0.1"
                  value={formData.designOperatingStressMpa ?? ""}
                  onChange={(e) =>
                    handleNumberChange(
                      "designOperatingStressMpa",
                      e.target.value
                    )
                  }
                  required
                />
                <p className="text-xs text-gray-500 mt-1">
                  用于计算水平放线张力
                </p>
              </div>
              <div>
                <Label htmlFor="thermalExpansionCoeffPerC">
                  线膨胀系数 (/°C)
                </Label>
                <Input
                  id="thermalExpansionCoeffPerC"
                  type="number"
                  step="1e-7"
                  value={formData.thermalExpansionCoeffPerC ?? ""}
                  onChange={(e) =>
                    handleNumberChange(
                      "thermalExpansionCoeffPerC",
                      e.target.value
                    )
                  }
                />
              </div>
              <div>
                <Label htmlFor="elasticModulusMpa">弹性模量 (MPa)</Label>
                <Input
                  id="elasticModulusMpa"
                  type="number"
                  step="1"
                  value={formData.elasticModulusMpa ?? ""}
                  onChange={(e) =>
                    handleNumberChange("elasticModulusMpa", e.target.value)
                  }
                />
              </div>
            </div>
            <div>
              <Label htmlFor="notes">备注</Label>
              <Textarea
                id="notes"
                value={formData.notes}
                onChange={(e) => handleChange("notes", e.target.value)}
                rows={3}
              />
            </div>
            <div className="flex justify-end gap-3 pt-4">
              <Button type="button" variant="outline" onClick={onCancel}>
                取消
              </Button>
              <Button type="submit">保存</Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

// 主组件 - 改为表格模式并添加分页
export default function ConductorSpecManager() {
  const [specs, setSpecs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingSpec, setEditingSpec] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");
  const { toast } = useToast();

  // 加载数据
  const loadSpecs = useCallback(async () => {
    setIsLoading(true);
    try {
      const data = await ConductorSpecAPI.getList();
      setSpecs(data.data);
    } catch (error) {
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载导线规格数据。",
      });
    }
    setIsLoading(false);
  }, [toast]);

  useEffect(() => {
    loadSpecs();
  }, [loadSpecs]);

  // 处理表单提交
  const handleSubmit = async (formData) => {
    try {
      if (editingSpec) {
        await ConductorSpecAPI.update(editingSpec.id, formData);
        toast({ title: "更新成功" });
      } else {
        await ConductorSpecAPI.create(formData);
        toast({ title: "创建成功" });
      }
      setShowForm(false);
      setEditingSpec(null);
      loadSpecs();
    } catch (error) {
      toast({
        variant: "destructive",
        title: "操作失败",
        description: error.message,
      });
    }
  };

  // 处理删除
  const handleDelete = async (id) => {
    if (window.confirm("确定要删除此规格吗？")) {
      try {
        await ConductorSpecAPI.delete(id);
        toast({ title: "删除成功" });
        loadSpecs();
      } catch (error) {
        toast({
          variant: "destructive",
          title: "删除失败",
          description: error.message,
        });
      }
    }
  };

  // 计算导线比载
  const calculateUnitLoad = (spec) => {
    if (spec.weightPerMeterNPerM > 0 && spec.crossSectionalAreaMm2 > 0) {
      return (spec.weightPerMeterNPerM / spec.crossSectionalAreaMm2).toFixed(6);
    }
    if (spec.unitLoadNPerMMm2 !== null && spec.unitLoadNPerMMm2 !== undefined) {
      return spec.unitLoadNPerMMm2.toFixed(6);
    }
    return "未知";
  };

  // 筛选数据
  const filteredSpecs = useMemo(() => {
    if (!searchTerm) return specs;

    const term = searchTerm.toLowerCase();
    return specs.filter(
      (spec) =>
        spec.model?.toLowerCase().includes(term) ||
        spec.type?.toLowerCase().includes(term) ||
        (spec.notes && spec.notes.toLowerCase().includes(term))
    );
  }, [specs, searchTerm]);

  // 分页处理
  const totalItems = filteredSpecs.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentSpecs = filteredSpecs.slice(indexOfFirstItem, indexOfLastItem);

  // 分页控制函数
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1);
  };

  // 渲染分页组件
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  // 导线类型标签映射
  const typeLabels = {
    ACSR: "钢芯铝绞线",
    AAC: "全铝绞线",
    AAAC: "全铝合金绞线",
    ACAR: "铝包钢芯铝绞线",
    ACCC: "碳纤维复合芯导线",
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <h3 className="text-xl font-bold">导线规格库</h3>
        <div className="flex w-full md:w-auto gap-3">
          <div className="relative flex-1 md:flex-none md:w-64">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="搜索型号或类型..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <Button
            onClick={() => {
              setEditingSpec(null);
              setShowForm(true);
            }}
          >
            <Plus className="w-4 h-4 mr-2" />
            新建规格
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div className="text-center py-16 px-4 text-gray-500 border rounded-lg bg-gray-50 border-gray-200">
          加载中...
        </div>
      ) : totalItems > 0 ? (
        <div className="rounded-lg border border-gray-200 overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 border-b border-gray-200">
                <TableRow>
                  <TableHead className="w-[200px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    导线型号
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    导线类型
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    额定拉断力 (kN)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    总截面积 (mm²)
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    外径 (mm)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    单位重量 (N/m)
                  </TableHead>
                  <TableHead className="w-[140px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    导线比载 (N/(m·mm²))
                  </TableHead>
                  <TableHead className="w-[140px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    设计运行应力 (MPa)
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-right text-sm font-semibold text-gray-700">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {currentSpecs.map((spec) => (
                  <TableRow
                    key={spec.id}
                    className="transition-colors duration-150 border-b border-gray-100 last:border-0 hover:bg-gray-50"
                  >
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-medium">
                      {spec.model}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm">
                      {typeLabels[spec.type] || spec.type}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm font-mono">
                      {spec.breakingForceKn ?? "-"}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm font-mono">
                      {spec.crossSectionalAreaMm2 ?? "-"}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm font-mono">
                      {spec.outerDiameterMm ?? "-"}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm font-mono">
                      {spec.weightPerMeterNPerM ?? "-"}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-green-600 text-sm font-mono">
                      {calculateUnitLoad(spec)}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm font-mono">
                      {spec.designOperatingStressMpa ?? "-"}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-gray-600 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                          >
                            <MoreHorizontal className="w-4 h-4" />
                            <span className="sr-only">操作菜单</span>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-[140px]">
                          <DropdownMenuItem
                            onClick={() => {
                              setEditingSpec(spec);
                              setShowForm(true);
                            }}
                          >
                            <Edit className="w-4 h-4 mr-2" />
                            编辑
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDelete(spec.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          {renderPagination()}
        </div>
      ) : (
        <div className="text-center py-12 text-gray-500 bg-white rounded-lg shadow-sm border border-gray-200">
          <Cable className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p className="text-lg font-medium mb-2">暂无导线规格数据</p>
          <Button
            variant="link"
            onClick={() => {
              setEditingSpec(null);
              setShowForm(true);
            }}
          >
            点击创建第一条规格
          </Button>
        </div>
      )}

      {showForm && (
        <ConductorSpecForm
          spec={editingSpec}
          onSubmit={handleSubmit}
          onCancel={() => {
            setShowForm(false);
            setEditingSpec(null);
          }}
        />
      )}
    </div>
  );
}
